package com.kk.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kk.common.PageResult;
import com.kk.exceptions.BusinessException;
import com.kk.mapper.SysRoleMapper;
import com.kk.pojo.entity.SysRole;
import com.kk.pojo.entity.SysUserRole;
import com.kk.pojo.request.RoleRequest;
import com.kk.service.SysRoleService;
import com.kk.service.SysUserRoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.math.BigInteger;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author kl
 * @version 1.0
 * @description: TODO
 * @date 2025/10/13 下午5:52
 */
@Service
@RequiredArgsConstructor
public class SysRoleServiceImpl  extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    private final SysUserRoleService sysUserRoleService;

    @Override
    public List<SysRole> findRoleByUserName(List<BigInteger> roleIds) {
        return this.listByIds(roleIds);
    }

    @Override
    public Set<String> getUserRoleCodes(BigInteger userId) {
        // ✅ 使用连表查询，一次性获取用户角色
        List<SysRole> roles = this.baseMapper.selectRolesByUserId(userId);
        return roles.stream()
                .map(SysRole::getRoleCode)
                .collect(Collectors.toSet());
    }
    @Override
    public void assignRoleToUser(BigInteger userId) {
        SysRole defaultRole = this.getOne(
                new LambdaQueryWrapper<SysRole>()
                        .eq(SysRole::getRoleCode, "ROLE_USER")
        );

        if (defaultRole != null) {
            SysUserRole userRole = new SysUserRole();
            userRole.setUserId(userId);
            userRole.setRoleId(defaultRole.getId());
            boolean save = sysUserRoleService.save(userRole);
            if (!save){
                throw new BusinessException("分配角色失败");
            }
        } else {
            throw new BusinessException("分配角色失败");
        }
    }

    @Override
    public PageResult<SysRole> rolePage(RoleRequest request) {
        // 构建查询语句
        LambdaQueryWrapper<SysRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.hasText(request.getRoleName()),SysRole::getRoleName,request.getRoleName())
                .like(StringUtils.hasText(request.getDescription()),SysRole::getDescription,request.getDescription())
                .eq(!ObjectUtils.isEmpty(request.getStatus()),SysRole::getStatus,request.getStatus())
                .orderByDesc(SysRole::getCreateTime);
        // 执行分页查询
        Page<SysRole> page = this.page(new Page<>(request.getPageNum(), request.getPageSize()), queryWrapper);
        // 因为没有什么隐私数据，而且一般只有最高层管理员有这个权限，所以就不封装VO了，直接返回
        return  PageResult.of(page);
    }


}
